package com.hyc.myvideo.ui.activity.live;

import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.alivc.player.AliVcMediaPlayer;
import com.alivc.player.MediaPlayer;
import com.hyc.myvideo.R;
import com.hyc.myvideo.data.adapter.PlayerAdapter;
import com.hyc.myvideo.ui.base.BaseFActivity;
import com.hyc.myvideo.ui.base.BaseFragment;
import com.hyc.myvideo.widget.viewpager.NoScrollViewPager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import timber.log.Timber;

/**
 * 直播视频界面
 * @author gyb
 * @version 1.0
 * @created 2017/07/27
 */
public class PlayerActivity extends BaseFActivity {
    @BindView(R.id.error_info)
    TextView textViewError;
    @BindView(R.id.view_pager) NoScrollViewPager viewPager;
    private ArrayList<BaseFragment> listFragments ;
    public static final int STATUS_START = 1;
    public static final int STATUS_STOP = 2;
    public static final int STATUS_PAUSE = 3;
    public static final int STATUS_RESUME = 4;

    public static final int CMD_START = 1;
    public static final int CMD_STOP = 2;
    public static final int CMD_PAUSE = 3;
    public static final int CMD_RESUME = 4;
    public static final int CMD_VOLUME = 5;
    public static final int CMD_SEEK = 6;

    public static final int TEST = 0;


    private AliVcMediaPlayer mPlayer = null;
    private SurfaceHolder mSurfaceHolder = null;
    private SurfaceView mSurfaceView = null;
    private int mPlayingIndex = -1;
    private StringBuilder msURI = new StringBuilder("");
    private int mPosition = 0;
    private PlayerControl mPlayerControl = null;
    private PowerManager.WakeLock mWakeLock = null;
    private StatusListener mStatusListener = null;
    private boolean isLastWifiConnected = false;

    // 标记播放器是否已经停止
    private boolean isStopPlayer = false;
    // 标记播放器是否已经暂停
    private boolean isPausePlayer = false;
    //用来控制应用前后台切换的逻辑
    private boolean isCurrentRunningForeground = true;

    // 重点:发生从wifi切换到4g时,提示用户是否需要继续播放,此处有两种做法:
    // 1.从历史位置从新播放
    // 2.暂停播放,因为存在网络切换,续播有时会不成功
    private BroadcastReceiver connectionReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager connectMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
            NetworkInfo mobNetInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            NetworkInfo wifiNetInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            Timber.i("mobile " + mobNetInfo.isConnected() + " wifi " + wifiNetInfo.isConnected());
            if (!isLastWifiConnected && wifiNetInfo.isConnected()) {
                isLastWifiConnected = true;
            }
            if (isLastWifiConnected && mobNetInfo.isConnected() && !wifiNetInfo.isConnected()) {
                isLastWifiConnected = false;
                if (mPlayer != null) {
                    mPosition = mPlayer.getCurrentPosition();
                    // 重点:新增接口,此处必须要将之前的surface释放掉
                    mPlayer.releaseVideoSurface();
                    mPlayer.stop();
                    mPlayer.destroy();
                    mPlayer = null;
                }
                dialog();
            }
        }
    };

    protected void dialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(PlayerActivity.this);
        builder.setMessage("确认继续播放吗？");
        builder.setTitle("提示");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                initSurface();

            }
        });

        builder.setNegativeButton("退出", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                PlayerActivity.this.finish();
            }
        });

        builder.create().show();
    }

    public interface StatusListener {
        int notifyStatus(int status);
    }

    void setStatusListener(StatusListener listener) {
        mStatusListener = listener;
    }

    private PlayerControl.ControllerListener mController = new PlayerControl.ControllerListener() {
        @Override
        public void notifyController(int cmd, int extra) {
            Message msg = Message.obtain();
            switch (cmd) {
                case PlayerControl.CMD_PAUSE:
                    msg.what = CMD_PAUSE;
                    break;
                case PlayerControl.CMD_RESUME:
                    msg.what = CMD_RESUME;
                    break;
                case PlayerControl.CMD_SEEK:
                    msg.what = CMD_SEEK;
                    msg.arg1 = extra;
                    break;
                case PlayerControl.CMD_START:
                    msg.what = CMD_START;
                    break;
                case PlayerControl.CMD_STOP:
                    msg.what = CMD_STOP;
                    break;
                case PlayerControl.CMD_VOLUME:
                    msg.what = CMD_VOLUME;
                    msg.arg1 = extra;
                    break;
                default:
                    break;
            }
            if (TEST != 0) {
                mTimerHandler.sendMessage(msg);
            }
        }
    };

    @Override
    public int getContentViewId() {
        return R.layout.activity_player;
    }
    @Override
    protected void initView() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(connectionReceiver, intentFilter);
        listFragments = new ArrayList<>();
        listFragments.add(new NoFragment());
        listFragments.add(new ChatFragment());
        viewPager.setAdapter(new PlayerAdapter(getSupportFragmentManager(),listFragments));
        viewPager.setCurrentItem(1);
        //直播聊天界面是否滑动
        viewPager.setCanScroll(true);
        mPlayingIndex = -1;
        if (TEST == 1) {
            mPlayerControl = new PlayerControl(this);
            mPlayerControl.setControllerListener(mController);
        }
        acquireWakeLock();
        initSurface();
    }
    @Override
    protected void initData() {
    }
    @Override
    protected void oNext(String resulte, String method) {
    }

    @Override
    protected void oError() {

    }


    private void acquireWakeLock() {
        if (mWakeLock == null) {
            PowerManager pMgr = (PowerManager) this.getSystemService(this.POWER_SERVICE);
            mWakeLock = pMgr.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK,"SmsSyncService.sync() wakelock.");
        }
        mWakeLock.acquire();
    }

    private void releaseWakeLock() {
        mWakeLock.release();
        mWakeLock = null;
    }


    private SurfaceHolder.Callback mSurfaceHolderCB = new SurfaceHolder.Callback() {
        @SuppressWarnings("deprecation")
        public void surfaceCreated(SurfaceHolder holder) {
            mSurfaceHolder.setFixedSize(displaysMetrics.widthPixels, displaysMetrics.heightPixels);// 设置分辨率
            holder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
            holder.setKeepScreenOn(true);
            Timber.i("AlivcPlayer onSurfaceCreated.");
            // 重点:
            if (mPlayer != null) {
                // 对于从后台切换到前台,需要重设surface;部分手机锁屏也会做前后台切换的处理
                mPlayer.setVideoSurface(mSurfaceView.getHolder().getSurface());
            } else {
                // 创建并启动播放器
                startToPlay();
            }
            if (mPlayerControl != null)
                mPlayerControl.start();
            Timber.i("AlivcPlayeron SurfaceCreated over.");
        }

        public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
            Timber.i("onSurfaceChanged is valid ? " + holder.getSurface().isValid());
            if (mPlayer != null)
                mPlayer.setSurfaceChanged();
        }

        public void surfaceDestroyed(SurfaceHolder holder) {
            Timber.i("onSurfaceDestroy.");
            if (mPlayer != null) {
                mPlayer.releaseVideoSurface();
            }
        }
    };

    /**
     * 重点:初始化播放器使用的SurfaceView,此处的SurfaceView采用动态添加
     * @return 是否成功
     */
    private boolean initSurface() {
        FrameLayout frameContainer = (FrameLayout) findViewById(R.id.GLViewContainer);
        frameContainer.setBackgroundColor(Color.rgb(0, 0, 0));
        mSurfaceView = new SurfaceView(this);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT);
        params.gravity = Gravity.CENTER;
        mSurfaceView.setLayoutParams(params);
        //为避免重复添加,事先remove子view
        frameContainer.removeAllViews();
        frameContainer.addView(mSurfaceView);
        mSurfaceView.setZOrderOnTop(false);
        mSurfaceHolder = mSurfaceView.getHolder();
        mSurfaceHolder.addCallback(mSurfaceHolderCB);
        getPlayUrl();
        return true;
    }

    private int getVideoSourcePath(int curIndex, StringBuilder sURI) {
        //clear all now
        sURI.delete(0, sURI.length());
        int selected = -1;
        if (curIndex == -1) { //we play the selected item
//            sURI.append("rtmp://www.planeta-online.tv:1936/live/channel_4");
             sURI.append("rtmp://live.hkstv.hk.lxdns.com/live/hks");
            //sURI.append("http://pull2.inke.cn/live/1501465901558462.flv?ikHost=ws&ikOp=1&codecInfo=8192");
        }
        return selected;
    }

    private boolean startToPlay() {
        Timber.i("start play.");
        textViewError.setText("");
        if (mPlayer == null) {
            // 初始化播放器
            mPlayer = new AliVcMediaPlayer(this, mSurfaceView);
            mPlayer.setErrorListener(new VideoErrorListener());
            mPlayer.setInfoListener(new VideoInfolistener());
            mPlayer.setCompletedListener(new VideoCompletelistener());
            mPlayer.setVideoSizeChangeListener(new VideoSizeChangelistener());
            // 如果同时支持软解和硬解是有用
            Bundle bundle = (Bundle) getIntent().getExtras();
            mPlayer.setDefaultDecoder(1);
            // 重点: 在调试阶段可以使用以下方法打开native log
            mPlayer.enableNativeLog();
            if (mPosition != 0) {
                mPlayer.seekTo(mPosition);
            }
        }
        mPlayer.prepareAndPlay(msURI.toString());

        if (mStatusListener != null)
            mStatusListener.notifyStatus(STATUS_START);
        return true;

    }

    /***
     * 错误提示
     * @param err
     * @param bshow
     */
    private void report_error(String err, boolean bshow) {
        if (textViewError.getVisibility() == View.GONE && !bshow) {
            return;
        }
        textViewError.setVisibility(bshow ? View.VISIBLE : View.GONE);
        textViewError.setText(err);
        textViewError.setTextColor(Color.RED);
        return;
    }

    //pause the video
    private void pause() {
        if (mPlayer != null) {
            mPlayer.pause();
            isPausePlayer = true;
            if (mStatusListener != null)
                mStatusListener.notifyStatus(STATUS_PAUSE);
        }
    }

    //start the video
    private void start() {
        if (mPlayer != null) {
            mPlayer.play();
            if (mStatusListener != null)
                mStatusListener.notifyStatus(STATUS_RESUME);
        }
    }

    //stop the video
    private void stop() {
        Timber.i("AudioRender: stop play");
        if (mPlayer != null) {
            mPlayer.stop();
            if (mStatusListener != null)
                mStatusListener.notifyStatus(STATUS_STOP);
            mPlayer.destroy();
            mPlayer = null;
        }
    }
    private void getPlayUrl() {
        mPlayingIndex = getVideoSourcePath(mPlayingIndex, msURI);
    }
    /**
     * 错误处理监听器
     */
    private class VideoErrorListener implements MediaPlayer.MediaPlayerErrorListener {
        public void onError(int what, int extra) {
            int errCode = 0;
            if (mPlayer == null) {
                return;
            }
            errCode = mPlayer.getErrorCode();
            switch (errCode) {
                case MediaPlayer.ALIVC_ERR_LOADING_TIMEOUT:
                    report_error("缓冲超时,请确认网络连接正常后重试", true);
                    mPlayer.reset();
                    break;
                case MediaPlayer.ALIVC_ERR_NO_INPUTFILE:
                    //report_error("no input file", true);
                    mPlayer.reset();
                    break;
                case MediaPlayer.ALIVC_ERR_NO_VIEW:
                    // report_error("no surface", true);
                    mPlayer.reset();
                    break;
                case MediaPlayer.ALIVC_ERR_INVALID_INPUTFILE:
                    report_error("视频资源或者网络不可用", true);
                    mPlayer.reset();
                    break;
                case MediaPlayer.ALIVC_ERR_NO_SUPPORT_CODEC:
                    //report_error("no codec", true);
                    mPlayer.reset();
                    break;
                case MediaPlayer.ALIVC_ERR_FUNCTION_DENIED:
                    //report_error("no priority", true);
                    mPlayer.reset();
                    break;
                case MediaPlayer.ALIVC_ERR_UNKNOWN:
                    // report_error("unknown error", true);
                    mPlayer.reset();
                    break;
                case MediaPlayer.ALIVC_ERR_NO_NETWORK:
                    report_error("视频资源或者网络不可用", true);
                    mPlayer.reset();
                    break;
                case MediaPlayer.ALIVC_ERR_ILLEGALSTATUS:
                    // report_error("illegal call", true);
                    break;
                case MediaPlayer.ALIVC_ERR_NOTAUTH:
                    //report_error("auth failed", true);
                    break;
                case MediaPlayer.ALIVC_ERR_READD:
                    report_error("资源访问失败,请重试", true);
                    mPlayer.reset();
                    break;
                default:
                    break;

            }
        }
    }

    /**
     * 信息通知监听器:重点是缓存开始/结束
     */
    private class VideoInfolistener implements MediaPlayer.MediaPlayerInfoListener {
        public void onInfo(int what, int extra) {
            Timber.i("onInfo what = " + what + " extra = " + extra);
            switch (what) {
                case MediaPlayer.MEDIA_INFO_UNKNOW:
                    break;
                case MediaPlayer.MEDIA_INFO_BUFFERING_START:
                    //pause();
                    //show_buffering_ui(true);
                    break;
                case MediaPlayer.MEDIA_INFO_BUFFERING_END:
                    //start();
                    //show_buffering_ui(false);
                    break;
                case MediaPlayer.MEDIA_INFO_TRACKING_LAGGING:
                    break;
                case MediaPlayer.MEDIA_INFO_NETWORK_ERROR:
                    //report_error("�������!", true);
                    break;
                case MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START:
                    if (mPlayer != null)
                        Timber.i("on Info first render start : " + ((long) mPlayer.getPropertyDouble(AliVcMediaPlayer.FFP_PROP_DOUBLE_1st_VFRAME_SHOW_TIME, -1) - (long) mPlayer.getPropertyDouble(AliVcMediaPlayer.FFP_PROP_DOUBLE_OPEN_STREAM_TIME, -1)));
                    break;
            }
        }
    }

    /**
     * 视频播完监听器
     */
    private class VideoCompletelistener implements MediaPlayer.MediaPlayerCompletedListener {
        public void onCompleted() {
            Timber.i("视频播完啦");
            AlertDialog.Builder builder = new AlertDialog.Builder(PlayerActivity.this);
            builder.setMessage("播放结束");
            builder.setTitle("提示");
            builder.setNegativeButton("退出", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    PlayerActivity.this.finish();
                }
            });

            builder.create().show();
        }
    }

    /**
     * 视频大小变化监听器
     */
    private class VideoSizeChangelistener implements MediaPlayer.MediaPlayerVideoSizeChangeListener {
        public void onVideoSizeChange(int width, int height) {
            int vWidth = mPlayer.getVideoWidth();
            int vHeight = mPlayer.getVideoHeight();
            if(width > displaysMetrics.widthPixels || height > displaysMetrics.heightPixels){
                //如果video的宽或者高超出了当前屏幕的大小，则要进行缩放
                float wRatio = (float)vWidth/(float)displaysMetrics.widthPixels;
                float hRatio = (float)vHeight/(float)displaysMetrics.heightPixels;
                //选择大的一个进行缩放
                float ratio = Math.max(wRatio, hRatio);
                vWidth = (int)Math.ceil((float)vWidth/ratio);
                vHeight = (int)Math.ceil((float)vHeight/ratio);
                //设置surfaceView的布局参数
                mSurfaceHolder.setFixedSize(vWidth,vHeight);
//                mSurfaceView.setLayoutParams(new FrameLayout.LayoutParams(vWidth, vHeight));
            }

        }
    }
    @Override
    protected void onDestroy() {
        Timber.i("AudioRender: onDestroy");
        if (mPlayer != null) {
            mTimerHandler.removeCallbacks(mRunnable);
        }
        releaseWakeLock();

        if (connectionReceiver != null) {
            unregisterReceiver(connectionReceiver);
        }
        // 重点:在 activity destroy的时候,要停止播放器并释放播放器
        if (mPlayer != null) {
            mPosition = mPlayer.getCurrentPosition();
            stop();
            if (mPlayerControl != null)
                mPlayerControl.stop();
        }
        super.onDestroy();
        return;
    }

    @Override
    protected void onResume() {
        Timber.i("onResume");
        super.onResume();
        // 重点:如果播放器是从锁屏/后台切换到前台,那么调用player.stat
        if (mPlayer != null && !isStopPlayer && isPausePlayer) {
            isPausePlayer = false;
            mPlayer.play();
        }
    }

    @Override
    protected void onStart() {
        Timber.i("onStart.");
        super.onStart();
        if (!isCurrentRunningForeground) {
            Timber.i("切到前台 activity process");
        }
    }

    @Override
    protected void onPause() {
        Timber.i("onPause.");
        super.onPause();
        // 重点:播放器没有停止,也没有暂停的时候,在activity的pause的时候也需要pause
        if (!isStopPlayer && !isPausePlayer && mPlayer != null) {
            mPlayer.pause();
            isPausePlayer = true;
        }
    }

    @Override
    protected void onStop() {
        Timber.i("onStop.");
        super.onStop();
        isCurrentRunningForeground = isRunningForeground();
        if (!isCurrentRunningForeground) {
            Timber.i(">>>>>>>>>>>>>>>>>>>切到后台 activity process");
        }
    }

    private Handler mTimerHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case CMD_PAUSE:
                    pause();
                    break;
                case CMD_RESUME:
                    start();
                    break;
                case CMD_SEEK:
                    mPlayer.seekTo(msg.arg1);
                    break;
                case CMD_START:
                    startToPlay();
                    break;
                case CMD_STOP:
                    stop();
                    break;
                case CMD_VOLUME:
                    mPlayer.setVolume(msg.arg1);
                    break;
                default:
                    break;
            }
        }
    };
    Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            if (mPlayer != null && mPlayer.isPlaying())
                mTimerHandler.postDelayed(this, 1000);
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            isStopPlayer = true;
        }
        return super.onKeyDown(keyCode, event);
    }

    // 重点:判定是否在前台工作
    public boolean isRunningForeground() {
        ActivityManager activityManager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcessInfos = activityManager.getRunningAppProcesses();
        // 枚举进程
        for (ActivityManager.RunningAppProcessInfo appProcessInfo : appProcessInfos) {
            if (appProcessInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                if (appProcessInfo.processName.equals(this.getApplicationInfo().processName)) {
                    Timber.i("EntryActivity isRunningForeGround");
                    return true;
                }
            }
        }
        Timber.i("EntryActivity isRunningBackGround");
        return false;
    }





}
